//
//  BaseViewModel.swift
//  DouYu
//
//  Created by 王鹏宇 on 2018/4/11.
//  Copyright © 2018年 王鹏宇. All rights reserved.
//

import UIKit

class BaseViewModel{

    lazy var anchorGroups : [AnchorGroup] = [AnchorGroup]()
    func loadAnchorData(isGroupData : Bool, URLString : String,parameters : [String : Any]? = nil,finishedCallback : @escaping () -> ()) {
        
        NetworkManager.requestData(.get, URLString: URLString) { (result) in
            
            //对界面进行处理
            guard let resultDict = result as? [String : Any] else {
                return
            }
            
            guard let dataArray = resultDict["data"] as? [[String : Any]] else { return }
            
            //判断是否分组数据
            
            if isGroupData {
                
                for dict in dataArray {
                    guard let data = try?
                        JSONSerialization.data(withJSONObject:dict, options:.prettyPrinted) else { return }
                    
                    guard let model = try? JSONDecoder().decode(AnchorGroup.self, from: data) else { return }
                    self.anchorGroups.append(model)
                }
            }else {
                // 创建组
                
                guard let data = try?
                    JSONSerialization.data(withJSONObject:dataArray, options:.prettyPrinted) else { return }
                
                guard let model = try? JSONDecoder().decode(AnchorGroup.self, from: data) else { return }
                
                self.anchorGroups.append(model)
            }
            
            finishedCallback()
        }
    }
}
